export const toggleTheme = (event: any) => {
  if (!document.startViewTransition) {
    document.documentElement.classList.toggle('dark')
    return
  }

  // 延迟执行以释放主线程
  setTimeout(() => {
    const transition = document.startViewTransition(() => {
      document.documentElement.classList.toggle('dark')
    })

    transition.ready.then(() => {
      const { clientX, clientY } = event || {
        clientX: window.innerWidth / 2,
        clientY: window.innerHeight / 2
      }

      const endRadius = Math.hypot(
        Math.max(clientX, innerWidth - clientX),
        Math.max(clientY, innerHeight - clientY)
      )

      const clipPath = [
        `circle(0px at ${clientX}px ${clientY}px)`,
        `circle(${endRadius}px at ${clientX}px ${clientY}px)`
      ]

      const isDark = document.documentElement.classList.contains('dark')

      document.documentElement.animate(
        {
          clipPath: isDark ? clipPath.reverse() : clipPath
        },
        {
          duration: 450,
          easing: 'ease-in',
          pseudoElement: isDark
            ? '::view-transition-old(root)'
            : '::view-transition-new(root)'
        }
      )
    }).catch(console.error)
  }, 0)
}